import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { toast } from 'sonner';
import ProjectForm from '@/components/project/project-form';

const ProjectFormPage = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [project, setProject] = useState(null);
  const [loading, setLoading] = useState(false);

  // 获取项目详情（编辑模式）
  useEffect(() => {
    if (id) {
      fetchProjectDetail();
    }
  }, [id]);

  const fetchProjectDetail = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 模拟项目数据
      const mockProject = {
        id: parseInt(id),
        project_code: 'PRJ-2024-001',
        project_name: '电商平台开发项目',
        project_type: '研发',
        priority: '高',
        status: '执行中',
        manager_name: '张三',
        client_info: 'ABC公司',
        start_date: '2024-01-15',
        end_date: '2024-06-30',
        budget: 500000,
        description: '开发一个现代化的电商平台，包含用户管理、商品管理、订单管理等功能。',
        objectives: '1. 提升用户体验\n2. 提高系统性能\n3. 增加销售转化率',
        risk_level: '中',
        team_members: ['张三', '李四', '王五', '赵六']
      };
      
      setProject(mockProject);
    } catch (error) {
      toast.error('获取项目详情失败');
      console.error('获取项目详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (formData) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      if (id) {
        // 更新项目
        console.log('更新项目:', formData);
        toast.success('项目更新成功');
      } else {
        // 创建项目
        console.log('创建项目:', formData);
        toast.success('项目创建成功');
      }
      
      navigate('/project-management/project-list');
    } catch (error) {
      toast.error('保存失败');
      console.error('保存项目失败:', error);
    }
  };

  const handleCancel = () => {
    navigate('/project-management/project-list');
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="flex items-center gap-2">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
          <span>加载中...</span>
        </div>
      </div>
    );
  }

  return (
    <ProjectForm
      project={project}
      onSubmit={handleSubmit}
      onCancel={handleCancel}
    />
  );
};

export default ProjectFormPage; 